package com.jtech.together.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.jtech.together.R;
import com.jtech.together.model.event.AddTrendsEvent;
import com.jtech.together.mvp.contract.AddTrendsContract;
import com.jtech.together.mvp.presenter.AddTrendsPresenter;
import com.jtech.together.util.Bus;
import com.jtech.together.util.DeviceUtils;
import com.jtech.together.util.ImageSelect;
import com.jtech.together.util.LocationSelect;
import com.jtech.together.view.activity.base.BaseActivity;
import com.jtech.together.view.adapter.TrendsImageAdapter;
import com.jtech.together.view.weight.dialog.CustomProgressDialog;
import com.jtechlib2.listener.OnItemClickListener;
import com.jtechlib2.view.JRecyclerView;
import com.jtechlib2.view.RecyclerHolder;
import com.umeng.analytics.MobclickAgent;

import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import cn.bmob.v3.datatype.BmobGeoPoint;

/**
 * 增加动态
 * Created by wuxubaiyang on 2017/5/11.
 */
public class AddTrendsActivity extends BaseActivity implements AddTrendsContract.View, View.OnClickListener, Toolbar.OnMenuItemClickListener, OnItemClickListener {
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.edittext_add_trends_content)
    EditText editTextContent;
    @Bind(R.id.jrecyclerview_add_trends_images)
    JRecyclerView jRecyclerView;
    @Bind(R.id.textview_add_trends_location)
    TextView textViewLocation;

    private AddTrendsContract.Presenter presenter;
    private TrendsImageAdapter trendsImageAdapter;

    private BmobGeoPoint location;
    private String address;

    @Override
    protected void initVariables(Bundle bundle) {
        //绑定P类
        presenter = new AddTrendsPresenter(getActivity(), this, bundle);
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        setContentView(R.layout.activity_add_trends);
        //设置标题栏
        setSupportActionBar(toolbar);
        //设置标题栏菜单点击事件
        toolbar.setOnMenuItemClickListener(this);
        //设置后退按钮点击事件
        toolbar.setNavigationOnClickListener(this);
        //设置layoutmanager
        jRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 4));
        //设置适配器
        int defaultPadding = getResources().getDimensionPixelSize(R.dimen.default_padding);
        int itemSize = (DeviceUtils.getScreenWidth(getActivity()) - defaultPadding * 2) / 4;
        trendsImageAdapter = new TrendsImageAdapter(getActivity(), itemSize);
        jRecyclerView.setAdapter(trendsImageAdapter);
        //设置item点击事件
        jRecyclerView.setOnItemClickListener(this);
    }

    @Override
    protected void loadData() {
    }

    /**
     * 提交动态
     *
     * @return
     */
    private boolean submit() {
        String content = editTextContent.getText().toString();
        List<String> images = trendsImageAdapter.getImageList();
        //至少有一种数据，文本内容或图片
        if (TextUtils.isEmpty(content) && images.size() == 0) {
            Snackbar.make(toolbar, "至少填写一种信息", Snackbar.LENGTH_SHORT).show();
            return false;
        }
        //发送请求
        presenter.publishTrends(content, images, location, address);
        String message = "正在发布动态";
        if (trendsImageAdapter.getRealDatasSize() > 0) {
            message = "正在发布动态(1/" + trendsImageAdapter.getRealDatasSize() + ")";
        }
        CustomProgressDialog.showProgressDialog(getActivity(), message);
        return true;
    }

    @Override
    public void updateImageUrl(String key, String imageUrl, int position, int max) {
        trendsImageAdapter.replaceItem(key, imageUrl);
        //更新进度dialog文本
        CustomProgressDialog.updataMessage("正在发布动态(" + position + "/" + max + ")");
    }

    @Override
    public void publishSuccess(String objectId) {
        Bus.get().post(new AddTrendsEvent(objectId));
        CustomProgressDialog.dismissProgressDialog();
        onBackPressed();
    }

    @Override
    public void publishFail(String error) {
        CustomProgressDialog.dismissProgressDialog();
        Snackbar.make(toolbar, error, Snackbar.LENGTH_SHORT).show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        toolbar.inflateMenu(R.menu.menu_done);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public void onClick(View v) {
        //后退
        onBackPressed();
    }

    /**
     * 位置选择监听
     */
    @OnClick(R.id.textview_add_trends_location)
    public void onLocationClick() {
        LocationSelect.select(getActivity());
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.done://完成
                return submit();
        }
        return false;
    }

    @Override
    public void onItemClick(RecyclerHolder holder, View view, int position) {
        if (trendsImageAdapter.isAddView(holder.getAdapterPosition())) {
            ImageSelect.multiSelect(getActivity(), false, trendsImageAdapter.getLastCount());
        } else {
            trendsImageAdapter.removeItem(holder.getAdapterPosition());
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            //判断是否为图片选择返回
            if (ImageSelect.isRequestImageResult(requestCode)) {
                List<String> images = ImageSelect.getRequestImage(data);
                if (null != images && images.size() > 0) {
                    trendsImageAdapter.addItem(images);
                }
            } else if (LocationSelect.isRequestLocationResult(requestCode)) {//判断是否为位置选择返回
                String address = LocationSelect.getRequestLocationAddress(data);
                double[] location = LocationSelect.getRequestLocation(data);
                if (!TextUtils.isEmpty(address) && null != location) {
                    this.address = address;
                    this.location = new BmobGeoPoint(location[0], location[1]);
                    //显示位置信息
                    textViewLocation.setText(address);
                }
            }
        }
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(TAG);
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(TAG);
        MobclickAgent.onPause(this);
    }
}